package com.fruit.service.pay.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.BillConstant;
import com.fruit.constants.GoodsConstant;
import com.fruit.constants.OrderConstant;
import com.fruit.constants.PayConstant;
import com.fruit.mapper.goods.GoodsMapper;
import com.fruit.mapper.order.DshOrderMapper;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.mapper.shopping.ShoppingMapper;
import com.fruit.mapper.user.UserMapper;
import com.fruit.pojo.common.OperatingConfig;
import com.fruit.pojo.goods.Goods;
import com.fruit.pojo.goods.GoodsTradePrice;
import com.fruit.pojo.order.Bill;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderConfig;
import com.fruit.pojo.order.OrderGoods;
import com.fruit.pojo.order.OrderInvoice;
import com.fruit.pojo.order.OrderReceiver;
import com.fruit.pojo.pay.PayInfo;
import com.fruit.pojo.pay.TransactionFlow;
import com.fruit.pojo.shopping.Shopping;
import com.fruit.pojo.user.Address;
import com.fruit.pojo.user.ComAccount;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.pay.PayManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.DataUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.fruit.util.ShortUrlUtil;


/** 支付
 * 修改时间：2016.07.15
 */
@Service("payService")
public class PayService implements PayManager{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private ShoppingMapper shoppingMapper;
	
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Autowired
	private PayMapper payMapper;
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private DshOrderMapper dshOrderMapper;
	
	@Override
	public Map<String, Object> saveConfirmPay(PayInfo pi) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		//验证参数
		if(pi.getKeys() == null || pi.getKeys().length == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		int size = pi.getKeys().length;
		if(pi.getLeaveMessage() == null || pi.getLeaveMessage().length != size){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		if(pi.getShoppingIds() == null || pi.getShoppingIds().length == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		
		
		if(!PayConstant.PAY_TYPE_ALL.equals(pi.getPayType())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pay_type_error", "支付类型错误!"));
			return resMap;	
		}
		if(!PayConstant.PAY_MODE_TRANSFER.equals(pi.getPayMode())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pay_mode_error", "支付方式错误!"));
			return resMap;	
		}
		BigDecimal totalPrice = DataUtil.getBigDecimal(pi.getTotalPrice());
		if(totalPrice.compareTo(BigDecimal.ZERO) <=0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		
		if(pi.getAddressId() <= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "请选择收货地址!"));
			return resMap;
		}
		
		if(!GoodsConstant.ADVANCE_Y.equals(pi.getGoodsType()) && !GoodsConstant.ADVANCE_N.equals(pi.getGoodsType())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;			
		}
		
		UserInfo ui = userMapper.getUserById(pi.getUserId());
		if(ui == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在!"));
			return resMap;			
		}
		pi.setCompanyName(ui.getCompanyName());
		pi.setPhone(ui.getPhone());
		
		//查询收货地址
		Address address= userMapper.getAddress(pi.getAddressId());
		if(address == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "请选择收货地址!"));
			return resMap;
		}
		//查看购物车
		Shopping sp = new Shopping();
		sp.setUserId(pi.getUserId());
		sp.setIds(pi.getShoppingIds());
		List<Shopping> shoppingList = shoppingMapper.getShoppingListByIds(sp);
		if(shoppingList == null || shoppingList.size() == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "shopping_empty", "购物车为空!"));
			return resMap;
		}
		if(shoppingList.size() != pi.getShoppingIds().length){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!"));
			return resMap;
		}
		
		List<OrderConfig> orderConfigList = dshOrderMapper.getOrderConfig();
		if(orderConfigList == null || orderConfigList.size() != 1){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception_order_config", "系统繁忙!"));
			return resMap;
		}
		
		OrderConfig orderConfig = orderConfigList.get(0);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", sp.getUserId());
		params.put("state", OrderConstant.PAY_NO);
		
		int orderCancelCnt = orderMapper.getOrderCntByUserId(params);
		if(orderCancelCnt >= orderConfig.getOrderNotpayMaxNum()){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "order_cancel_max", "未支付订单数量达到上限，请先完成支付!"));
			return resMap;
		}
		
		Map<String,String> keyMap = new HashMap<String, String>();
		for(int i = 0; i<pi.getKeys().length; i++){
			keyMap.put(pi.getKeys()[i], CommonUtil.decode(pi.getLeaveMessage()[i], "utf-8"));
		}
		
		if(GoodsConstant.ADVANCE_Y.equals(pi.getGoodsType())){
			resMap = getOrderListTypeA(shoppingList, pi, keyMap);
		}else{
			
			resMap = getOrderListTypeS(shoppingList, pi, keyMap);
		}
		if(resMap.containsKey("result")){
			return resMap;
		}
		//删除购物车
		int delNum = shoppingMapper.delShopping(sp);
		if(delNum != sp.getIds().length){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
			return resMap;
		}
		//保存订单
		if(PayConstant.PAY_MODE_TRANSFER.equals(pi.getPayMode())){
			transferSaveInfo(resMap,pi,address);
		}
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> transferSaveInfo(Map<String, Object> resMap,PayInfo pi, Address address){

		List<Order> orderList = (List<Order>)resMap.get("orderList");
		StringBuffer remittanceCodes = new StringBuffer();
		StringBuffer transactionIds = new StringBuffer();
		StringBuffer orderCodes = new StringBuffer();
		for(int i=0;i<orderList.size();i++){
			Order order = orderList.get(i);
			//插入账单
			Bill b = new Bill();
			b.setUserId(pi.getUserId());
			b.setType(BillConstant.TYPE_CONSUME);
			b.setMoney(order.getTotalPrice());
			b.setMoneyState(BillConstant.MONEY_CUT);
			b.setState(BillConstant.STATE_NOT_HANDEL);
			b.setRemark(order.getRemark());
			b.setCreateTime(DateUtil.getTime());
			b.setUpdateTime(DateUtil.getTime());
			payMapper.saveBillDetail(b);
			//生成汇付识别码
			String remittanceCode = ShortUrlUtil.getCode(3, 3, b.getId());
			
			//插入交易流水
			TransactionFlow tf = new TransactionFlow();
			tf.setCodePre(DateUtil.getYear());
			tf.setCodeSuf(CustomUtil.codeSuf(3, pi.getUserId()));
			tf.setUserId(order.getUserId());
			tf.setPayMode(pi.getPayMode());
			tf.setPayType(pi.getPayType());
			tf.setRemittanceCode(remittanceCode);
			tf.setTotalPrice(order.getRealPrice());
			tf.setRemark(order.getRemark());
			tf.setType(BillConstant.TYPE_CONSUME);
			tf.setCreateTime(DateUtil.getTime());
			payMapper.saveTransactionFlow(tf);			
			
			//插入订单
			order.setTransactionId(tf.getId());
			payMapper.saveOrder(order);
			//插入收货信息
			OrderReceiver or = new OrderReceiver();
			or.setOrderId(order.getId());
			or.setProvinceId(address.getProvinceId());
			or.setCityId(address.getCityId());
			or.setCountryId(address.getCountryId());
			or.setReceiverName(address.getName());
			or.setReceiverPhone(address.getPhone());
			or.setReceiverAddress(address.getAddress());
			payMapper.saveOrderReceiver(or);
			//插入商品信息
			List<OrderGoods> ogList = order.getOrderGoods();
			for(OrderGoods og:ogList){
				og.setOrderId(order.getId());
				int uNum = payMapper.updateGoodsStockNum(og);
				if(uNum == 0){
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+og.getTitle()+"）库存不足", null, ResultInfo.ROLLBACK));
					return resMap;
				}
				payMapper.saveOrderGoods(og);
			}
			remittanceCodes.append(remittanceCode);
			transactionIds.append(tf.getId());
			orderCodes.append(order.getCodePre()+order.getId()+order.getCodeSuf());
			if(i != orderList.size() - 1){
				remittanceCodes.append(",");
				transactionIds.append(",");
				orderCodes.append(",");
			}			
			
			if(StringUtils.isNotEmpty(pi.getInvoiceType())){
				OrderInvoice oi = new OrderInvoice();
				oi.setOrderId(order.getId());
				oi.setType(pi.getInvoiceType());
				oi.setName(pi.getInvoiceName());
				oi.setIdentifyNumber(pi.getIdentifyNumber());
				payMapper.saveOrderInvoice(oi);
			}
			
		}
		pi.setCodePre(DateUtil.getYear());
		pi.setCodeSuf(CustomUtil.codeSuf(3, pi.getUserId()));
		pi.setRemittanceCode(remittanceCodes.toString());
		pi.setTransactionIds(transactionIds.toString());
		pi.setAddPrice(pi.getTotalPrice());
		pi.setBalancePrice(new BigDecimal(0));
		pi.setRemark("消费"+pi.getTotalPrice()+"元");
		pi.setType(BillConstant.TYPE_CONSUME);
		pi.setCreateTime(DateUtil.getTime());
		payMapper.savePayInfo(pi);
		pi.setOrderCodes(orderCodes.toString());
		pi.setCode(pi.getCodePre()+pi.getId()+pi.getCodeSuf());
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		resMap.put("pi",pi);
		return resMap;
	}
	
	public Map<String, Object> getOrderListTypeA(List<Shopping> shoppingList,PayInfo pi, Map<String,String> keyMap){
		Map<String, Object> resMap = new HashMap<String, Object>();
		List<Order> orderList = new ArrayList<Order>();
		List<String> keyList = new ArrayList<String>();
		BigDecimal totalPirce = new BigDecimal(0);
		for(Shopping shopping:shoppingList){
			Goods goods = goodsMapper.getGoodsDetail(shopping.getGoodsId());
			if(goods == null){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			if(!GoodsConstant.ADVANCE_Y.equals(goods.getIsAdvanceState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			//验证商品是否已下架
			if(GoodsConstant.STATE_DOWN.equals(goods.getState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）已下架"));
				return resMap;
			}
			
			String curTime = DateUtil.getTime();
			if(!(DateUtil.compareDate2(curTime,goods.getStartTime()) && DateUtil.compareDate2(goods.getEndTime(),curTime))){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "商品（"+goods.getTitle()+"）未上架或已下架!"));
				return resMap;
			}	
			
			List<OperatingConfig> ocList = payMapper.getOperatingConfig();
			if(ocList != null && ocList.size() ==1){
				OperatingConfig oc = ocList.get(0);
				long hsmTime = DateUtil.getHsmTime();
				
				if(hsmTime < oc.getMinTime() || hsmTime > oc.getMaxTime()){
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "operating_error", "已过运营时间!"));
					return resMap;
				}

			}
			
			//商品单位换算
			if(!StringUtils.equals(shopping.getUnit(), goods.getUnit())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "unit_error", "单位错误!"));
				return resMap;
			}
			int unitNum = shopping.getNum();
			//验证库存
			if(unitNum < goods.getMinShopNum()){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）起订量为"+goods.getMinShopNum()+goods.getUnitDesc()));
				return resMap;
			}
			
			//验证预售商品是否到期
			String advanceStartTime = goods.getAdvanceStartTime();
			Date advanceStartTimeD = DateUtil.fomatDateTime(advanceStartTime, "yyyy-MM-dd HH:mm:ss");
			//验证开始时间
			if(DateUtil.subtractTime(advanceStartTimeD,new Date()) > 0){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）预售未开始"));
				return resMap;
			}
			String advanceEndTime = goods.getAdvanceEndTime();
			Date advanceEndTimeD = DateUtil.fomatDateTime(advanceEndTime, "yyyy-MM-dd HH:mm:ss");
			//验证结束时间
			if(DateUtil.subtractTime(advanceEndTimeD, new Date()) <= 0){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）预售已结束"));
				return resMap;
			}
			//计算批发价
			Map<String, Object> params = new HashMap<String, Object>();
			params.clear();
			params.put("goodsId", goods.getId());
			params.put("num", shopping.getNum());
			List<GoodsTradePrice> gtpList = goodsMapper.getGoodsTradePrice(params);
			if(gtpList != null && gtpList.size() == 1){
				GoodsTradePrice gtp = gtpList.get(0);
				goods.setTradePrice(gtp.getPrice());
			}else{
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			if(!keyMap.containsKey(String.valueOf(goods.getId()))){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			//商品信息
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setGoodsId(goods.getId());
			orderGoods.setGoodsCode(goods.getCode());
			orderGoods.setTitle(goods.getTitle());
			orderGoods.setSubTitle(goods.getSubTitle());
			orderGoods.setGoodsThumb(goods.getThumb());
			orderGoods.setNumber(shopping.getNum());
			orderGoods.setUnitNumber(unitNum);
			orderGoods.setUnit(goods.getUnit());
			orderGoods.setBuyUnit(shopping.getUnit());
			orderGoods.setTradePrice(goods.getTradePrice());
			orderGoods.setRetailPrice(goods.getRetailPrice());
			orderGoods.setBidPrice(goods.getBidPrice());
			orderGoods.setIsAdvanceState(goods.getIsAdvanceState());
			orderGoods.setSpec(shopping.getSpec());
			orderGoods.setSpecDesc(shopping.getSpecDesc());
			//运费 待定
			Order order = new Order();
			order.setCodePre(DateUtil.getYear());
			order.setCodeSuf(CustomUtil.codeSuf(3, pi.getUserId()));
			order.setUserId(pi.getUserId());
			order.setSupplier(goods.getSupplier());
			order.setAddressId(goods.getAddressId());
			order.setType(OrderConstant.TYPE_GOODS);
			order.setState(OrderConstant.PAY_NO);
			order.setTransitPrice(new BigDecimal(0));
			order.setTotalPrice(orderGoods.getTradePrice().multiply(DataUtil.getBigDecimal(orderGoods.getNumber())));
			order.setRealPrice(order.getTotalPrice());
			order.setCreateTime(DateUtil.getTime());
			order.setLeaveMessage(keyMap.get(String.valueOf(goods.getId())));
			order.setExpectDeliveryTime(goods.getExpectDeliveryTime());
			order.setRemark(goods.getTitle());
			order.setIsAdvanceState(pi.getGoodsType());
			order.getOrderGoods().add(orderGoods);
			orderList.add(order);
			keyList.add(String.valueOf(goods.getId()));
			totalPirce = totalPirce.add(order.getTotalPrice());
		}
		
		if(pi.getTotalPrice().compareTo(totalPirce)!= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		
		resMap.put("orderList", orderList);
		resMap.put("keyList", keyList);
		return resMap;
		
	}

	public Map<String, Object> getOrderListTypeS(List<Shopping> shoppingList, PayInfo pi, Map<String,String> keyMap){
		Map<String, Object> resMap = new HashMap<String, Object>();
		List<Order> orderList = new ArrayList<Order>();
		List<String> keyList = new ArrayList<String>();
		Map<String, Order> orderMap= new HashMap<String, Order>();
		BigDecimal totalPirce = new BigDecimal(0);
		for(Shopping shopping:shoppingList){
			Goods goods = goodsMapper.getGoodsDetail(shopping.getGoodsId());
			if(goods == null){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			if(!GoodsConstant.ADVANCE_N.equals(goods.getIsAdvanceState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			//验证商品是否已下架
			if(GoodsConstant.STATE_DOWN.equals(goods.getState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）已下架"));
				return resMap;
			}
			
			String curTime = DateUtil.getTime();
			if(!(DateUtil.compareDate2(curTime,goods.getStartTime()) && DateUtil.compareDate2(goods.getEndTime(),curTime))){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "商品（"+goods.getTitle()+"）未上架或已下架!"));
				return resMap;
			}	
			
			List<OperatingConfig> ocList = payMapper.getOperatingConfig();
			if(ocList != null && ocList.size() ==1){
				OperatingConfig oc = ocList.get(0);
				long hsmTime = DateUtil.getHsmTime();
				
				if(hsmTime < oc.getMinTime() || hsmTime > oc.getMaxTime()){
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "operating_error", "已过运营时间!"));
					return resMap;
				}

			}
			
			//验证商品
			if(goods.getSupplier() == 0){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）参数错误"));
				return resMap;
			}
			
			//商品单位换算
			if(!StringUtils.equals(shopping.getUnit(), goods.getUnit())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "unit_error", "单位错误!"));
				return resMap;
			}
			int unitNum = shopping.getNum();
			//验证库存
			if(unitNum < goods.getMinShopNum()){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "商品（"+goods.getTitle()+"）起订量为"+goods.getMinShopNum()+goods.getUnitDesc()));
				return resMap;
			}
			
			//计算批发价
			Map<String, Object> params = new HashMap<String, Object>();
			params.clear();
			params.put("goodsId", goods.getId());
			params.put("num", shopping.getNum());
			List<GoodsTradePrice> gtpList = goodsMapper.getGoodsTradePrice(params);
			if(gtpList != null && gtpList.size() == 1){
				GoodsTradePrice gtp = gtpList.get(0);
				goods.setTradePrice(gtp.getPrice());
			}else{
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			String key = String.valueOf(goods.getSupplier());
			if(!keyMap.containsKey(key)){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
				return resMap;
			}
			
			//商品信息
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setGoodsId(goods.getId());
			orderGoods.setGoodsCode(goods.getCode());
			orderGoods.setTitle(goods.getTitle());
			orderGoods.setSubTitle(goods.getSubTitle());
			orderGoods.setGoodsThumb(goods.getThumb());
			orderGoods.setNumber(shopping.getNum());
			orderGoods.setUnitNumber(unitNum);
			orderGoods.setUnit(goods.getUnit());
			orderGoods.setBuyUnit(shopping.getUnit());
			orderGoods.setTradePrice(goods.getTradePrice());
			orderGoods.setRetailPrice(goods.getRetailPrice());
			orderGoods.setBidPrice(goods.getBidPrice());
			orderGoods.setIsAdvanceState(goods.getIsAdvanceState());
			orderGoods.setSpec(shopping.getSpec());
			orderGoods.setSpecDesc(shopping.getSpecDesc());
			
			Order order = null;
			if(orderMap.containsKey(key)){
				order = orderMap.get(key);
				order.setRemark(order.getRemark()+" "+goods.getTitle());
			}else{
				order = new Order();
				order.setCodePre(DateUtil.getYear());
				order.setCodeSuf(CustomUtil.codeSuf(3, pi.getUserId()));
				order.setUserId(pi.getUserId());
				order.setSupplier(goods.getSupplier());
				order.setAddressId(goods.getAddressId());
				order.setType(OrderConstant.TYPE_GOODS);
				order.setState(OrderConstant.PAY_NO);
				order.setCreateTime(DateUtil.getTime());
				order.setLeaveMessage(keyMap.get(key));
				order.setRemark(goods.getTitle());
				order.setExpectDeliveryTime(goods.getExpectDeliveryTime());
				order.setIsAdvanceState(pi.getGoodsType());
				keyList.add(key);
			}
			
			//运费 待定
			order.setTransitPrice(new BigDecimal(0));
			order.setTotalPrice(DataUtil.getBigDecimal(order.getTotalPrice()).add(orderGoods.getTradePrice().multiply(DataUtil.getBigDecimal(orderGoods.getNumber()))));
			order.setRealPrice(order.getTotalPrice());
			order.getOrderGoods().add(orderGoods);
			orderMap.put(key, order);
			totalPirce = totalPirce.add(order.getTotalPrice());
		}
		
		if(pi.getTotalPrice().compareTo(totalPirce)!= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		orderList.addAll(orderMap.values());
		if(keyList.size() != pi.getKeys().length){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!"));
			return resMap;
		}
		
		resMap.put("orderList", orderList);

		return resMap;
		
	}

	@Override
	public Map<String, Object> getPayInfo(PayInfo pi) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		ComAccount comAccount = orderMapper.getComAss();
		String code = pi.getCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		String codePre=code.substring(0,4);
		String codeSuf=code.substring(code.length()-7); 
		pi.setId(id);
		pi.setCodePre(codePre);
		pi.setCodeSuf(codeSuf);
		PayInfo payInfo = payMapper.getPayInfoById(pi);
		if(PayConstant.PAY_MODE_TRANSFER.equals(payInfo.getPayMode())){
			payInfo.setPayModeName("公司转账");
		}
		
		UserInfo ui = userMapper.getUserById(payInfo.getUserId());
		if(ui == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在!"));
			return resMap;			
		}
		
		Date createTime = DateUtil.fomatDateTime(payInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
		long sysdiff =  DateUtil.subtractTime(new Date(),createTime);
		long diff = DateUtil.getMillisecondDiff(sysdiff, 6);
		
		if(diff <=0 ){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pay_expire", "支付已过期!"));
			return resMap;
		}
		
		String phone = CustomUtil.subPhone(ui.getPhone());
		comAccount.setRemittanceDesc(StringUtils.replace(comAccount.getRemittanceDesc(), "#phone#", phone));
		resMap.put("diff", diff);
		resMap.put("comAccount", comAccount);
		resMap.put("payInfo", payInfo);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		return resMap;
	}

	@Override
	public Map<String, Object> getTransaction(Order or) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		String code = or.getOrderCode();
		long id= Long.parseLong(code.substring(4, code.length() - 7));
		Order order = dshOrderMapper.getOrder(id);
		TransactionFlow payInfo = payMapper.getTransactionById(order.getTransactionId());
		if(PayConstant.PAY_MODE_TRANSFER.equals(payInfo.getPayMode())){
			payInfo.setPayModeName("公司转账");
		}
		UserInfo ui = userMapper.getUserById(payInfo.getUserId());
		if(ui == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在!"));
			return resMap;			
		}
		
		Date createTime = DateUtil.fomatDateTime(payInfo.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
		long sysdiff =  DateUtil.subtractTime(new Date(),createTime);
		long diff = DateUtil.getMillisecondDiff(sysdiff, 6);
		
		if(diff <=0 ){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "pay_expire", "支付已过期!"));
			return resMap;
		}
		ComAccount comAccount = orderMapper.getComAss();
		String phone = CustomUtil.subPhone(ui.getPhone());
		comAccount.setRemittanceDesc(StringUtils.replace(comAccount.getRemittanceDesc(), "#phone#", phone));
		resMap.put("diff", diff);
		resMap.put("comAccount", comAccount);
		resMap.put("payInfo", payInfo);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
		return resMap;

	}


	
	
	
	
}
